/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.*;
import com.jeeplus.modules.ap.service.*;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.*;
import com.jeeplus.modules.tms.mapper.MaterialInformationsMapper;
import com.jeeplus.modules.tms.mapper.TmsAdditionalChargeMapper;
import com.jeeplus.modules.tms.mapper.TmsMaterialsInformationMapper;
import com.jeeplus.modules.tms.service.*;
import com.jeeplus.modules.tms.util.ExportTms;
import com.jeeplus.modules.tms.util.FileUtil;
import com.jeeplus.modules.tms.util.PrintWayBill;
import com.jeeplus.modules.wms.entity.Outbound;
import com.jeeplus.modules.wms.entity.Storehouse;
import com.jeeplus.modules.wms.mapper.StorehouseMapper;
import com.jeeplus.modules.wms.service.OutboundService;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 运单Controller
 * @author 李超辉
 * @version 2017-12-05
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/tmsWaybill")
public class TmsWaybillController extends BaseController {

	@Autowired
	private TmsWaybillService tmsWaybillService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private TmsMaterialsInformationMapper materialsInformationMapper;
	@Autowired
	private MaterialInformationsMapper informationsMapper;
	@Autowired
	private ReceiptService receiptService;
	@Autowired
	private AccidentService accidentService;
	@Autowired
	private TailAfterService afterService;
	@Autowired
	private NotnodeService notnodeService;
	@Autowired
	private OutboundService outboundService;
	@Autowired
	private StorehouseMapper storehouseMapper;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private UpCustomersService upCustomersService;
	@Autowired
	private TransportPlanningService service;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private MaterialInformationsMapper materialInformationsMapper;
	@Autowired
	private TransportPlanningService transportPlanningService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private AdvanceService advanceService;
	@Autowired
	private RecelService recelService;
	@Autowired
	private TmsAdditionalChargeMapper tmsAdditionalChargeMapper;
	@Autowired
	private BillAddService billAddService;
	@Autowired
	private YueService yueService;
	@Autowired
	private PlanningService planningService;
	@Autowired
	private LnsuranceService lnsuranceService;
	@Autowired
	private PolicyService policyService;
	@ModelAttribute
	public TmsWaybill get(@RequestParam(required=false) String id) {
		TmsWaybill entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tmsWaybillService.get(id);
		}
		if (entity == null){
			entity = new TmsWaybill();
		}
		return entity;
	}
	
	/**
	 * 运单列表页面
	 */
	@RequiresPermissions("tms:tmsWaybill:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/tmsWaybillList";
	}

	/**
	 * 运费支出
	 */
	@RequiresPermissions("tms:tmsWaybill:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/tms/4/tmsWaybillList";
	}

	/**
	 * 运单报表
	 */
	@RequiresPermissions("tms:tmsWaybill:list")
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/tms/6/tmsWaybillList";
	}

	/**
	 * 运单报表
	 */

	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/tms/5/tmsWaybillList";
	}



	@ResponseBody
	@RequestMapping(value = "tb")
	public AjaxJson tb(String bz,String name,String bd,String je,TmsWaybill t) throws Exception {
		AjaxJson ajaxJson=new AjaxJson();
			t.setBx("预投保");
		    tmsWaybillService.save(t);
			Lnsurance l=new Lnsurance();
			l.setStart(t.getContractDistance());
			l.setArrive(t.getArrive());
			l.setHwmc(bd);
			l.setName(name);
			l.setBz(bz);
			l.setJs(t.getZjs()+"");
			l.setZl(t.getWeight());
			l.setFhrq(t.getFhrq());
			l.setCph(t.getPlateNumber());
			l.setYdh(t.getCode());
			l.setYsfs(t.getTransportMode());
			l.setPro(t.getProjectName());
			l.setGsje(je);
			l.setPid(t.getId());
			l.setStatus("已创建");
		lnsuranceService.save(l);

		ajaxJson.setMsg("投保成功");
		return ajaxJson;
	}

	@ResponseBody
	@RequestMapping(value = "hzfk")
	public AjaxJson hzfk(String i,String yk,String xj,String number,String hd,String sm) throws Exception {
		AjaxJson ajaxJson=new AjaxJson();
		String[] ids=i.split(",");
         for(String id:ids){
			 TmsWaybill t=tmsWaybillService.get(id);
			 t.setHzjs("预处理");
			 tmsWaybillService.save(t);
			 Recel a =recelService.findUniqueByProperty("bill",i);
			 if(a!=null){
			 	break;
			 }
			 int sum=0;
			 Double b=0.0;
			 for(TmsMaterialsInformation m:t.getTmsMaterialsInformationList()){
				 int amount=Integer.parseInt(m.getLoadingQuantity());
				 Goods g=goodsService.get(m.getName().getId());
				 int bl=Integer.parseInt(g.getProportion());
				 int c=amount/bl;
				 sum+=c;
				 b+=Double.parseDouble(m.getWeight());
			 }
			 a=new Recel();
			 a.setNum(sum+"");
			 a.setWeight(b+"");
			 a.setStart(t.getContractDistance());
			 a.setNumber(number);
			 a.setJsdate(t.getStowageDate());
			 a.setDate(t.getStowageDate());
			 a.setCode(t.getCode());
			 a.setZccode(t.getForwardingPrice());
			 a.setPerson(t.getDriverName());
			 a.setCard(t.getPlateNumber());
			 a.setZcje(t.getRentingCost());
			 a.setDriver(t.getPayeeName());
			 a.setSfhd(hd);
			 a.setBill(id);
			 a.setStatus("已入账");
			 a.setRz(new Date());
			 a.setReceipt(t.getShipmentNumbers());
			 a.setPhone(t.getDriverPhone());
			 a.setArrive(t.getArriveCity());
			 a.setHdht(t.getKdPayment());
			 a.setHzht(t.getReceiptCalculate());
			 a.setHzxy(t.getRentingCost());
			 a.setMoney(xj);
			 a.setOil(yk);
			 a.setSfzje((Double.parseDouble(hd)+Double.parseDouble(yk)+Double.parseDouble(xj))+"");
			 a.setRemarks(sm);
			 a.setPro(UserUtils.getUseroffice());
			 a.setDelFlag("1");
			 NumberFormat nf = NumberFormat.getInstance();

			 double htzje=Double.parseDouble(t.getKdPayment())+Double.parseDouble(t.getReceiptCalculate())+Double.parseDouble(t.getRentingCost());
			 double zj=Double.parseDouble(hd)+Double.parseDouble(yk)+Double.parseDouble(xj)-htzje;
			 a.setZj(nf.format(zj).replaceAll(",",""));
			 a.setHtzje(nf.format(htzje).replaceAll(",",""));

			 recelService.save(a);
		 }

		ajaxJson.setMsg("过账成功");
	return ajaxJson;
	}

	@ResponseBody
	@RequestMapping(value = "getdetil")
	public String getdetil(String i){
		Advance a=advanceService.findUniqueByProperty("bill",i);
		Gson g=new Gson();
		return g.toJson(a).toString();
	}
	@ResponseBody
	@RequestMapping(value = "getdetil0")
	public String getdetil0(String i){
		Recel a=recelService.findUniqueByProperty("bill",i);
		Gson g=new Gson();
		return g.toJson(a).toString();
	}

	@ResponseBody
	@RequestMapping(value = "yfkqd")
	public AjaxJson yfkqd(String i){
		AjaxJson ajaxJson=new AjaxJson();
		Advance a=advanceService.findUniqueByProperty("bill",i);
		a.setDelFlag("0");
		advanceService.save(a);
		NumberFormat nf = NumberFormat.getInstance();
		Yue yue=yueService.findUniqueByProperty("pro",UserUtils.getUseroffice());
		yue.setXj(nf.format(Double.parseDouble(yue.getXj())-Double.parseDouble(a.getSfxj())).replaceAll(",",""));
		yue.setYk(nf.format(Double.parseDouble(yue.getYk())-Double.parseDouble(a.getSfyk())).replaceAll(",",""));
		yue.setZje(nf.format(Double.parseDouble(yue.getZje())-Double.parseDouble(a.getSfzje())).replaceAll(",",""));
		yueService.save(yue);
		TmsWaybill t=tmsWaybillService.get(i);
		t.setYfk("已过账");
		tmsWaybillService.save(t);
		return ajaxJson;
	}
	@ResponseBody
	@RequestMapping(value = "yfkqx")
	public AjaxJson yfkqx(String i){
		AjaxJson ajaxJson=new AjaxJson();
		Advance a=advanceService.findUniqueByProperty("bill",i);
		advanceService.delete(a);
		TmsWaybill t=tmsWaybillService.get(i);
		t.setYfk("未过账");
		tmsWaybillService.save(t);
		return ajaxJson;
	}

	@ResponseBody
	@RequestMapping(value = "hzqd")
	public AjaxJson hzqd(String i){
		AjaxJson ajaxJson=new AjaxJson();
		Recel a=recelService.findUniqueByProperty("bill",i);
		a.setDelFlag("0");
		recelService.save(a);
		NumberFormat nf = NumberFormat.getInstance();
		Yue yue=yueService.findUniqueByProperty("pro",UserUtils.getUseroffice());
		yue.setXj(nf.format(Double.parseDouble(yue.getXj())-Double.parseDouble(a.getSfhd())-Double.parseDouble(a.getMoney())).replaceAll(",",""));
		yue.setYk(nf.format(Double.parseDouble(yue.getYk())-Double.parseDouble(a.getOil())).replaceAll(",",""));
		yue.setZje(nf.format(Double.parseDouble(yue.getZje())-Double.parseDouble(a.getSfhd())-Double.parseDouble(a.getMoney())-Double.parseDouble(a.getOil())).replaceAll(",",""));
		yueService.save(yue);
		TmsWaybill t=tmsWaybillService.get(i);
		t.setHzjs("已过账");
		tmsWaybillService.save(t);
		return ajaxJson;
	}
	@ResponseBody
	@RequestMapping(value = "hzqx")
	public AjaxJson hzqx(String i){
		AjaxJson ajaxJson=new AjaxJson();
		Recel a=recelService.findUniqueByProperty("bill",i);
		recelService.delete(a);
		TmsWaybill t=tmsWaybillService.get(i);
		t.setHzjs("未过账");
		tmsWaybillService.save(t);
		return ajaxJson;
	}
	@ResponseBody
	@RequestMapping(value = "yfk")
	public AjaxJson yfk(String i,String xj,String yk,String kh,String sm, RedirectAttributes redirectAttributes) throws Exception {
		AjaxJson ajaxJson=new AjaxJson();
		String[] ids=i.split(",");
		for(String id:ids){
			TmsWaybill t=tmsWaybillService.get(id);
			t.setYfk("预处理");
			tmsWaybillService.save(t);
			Advance a =advanceService.findUniqueByProperty("bill",i);
			if(a!=null){
				break;
			}

			a=new Advance();
			a.setFkdate(new Date());
			a.setDate(t.getStowageDate());
			a.setCode(t.getCode());
			a.setNumber(t.getLoadingCardNumber());
			a.setZccode(t.getForwardingPrice());
			a.setPerson(t.getDriverName());
			a.setCard(t.getPlateNumber());
			a.setStatus("已入账");
			a.setRz(new Date());
			a.setPhone(t.getDriverPhone());
			a.setArrive(t.getArriveCity());
			String yk1=t.getLoadingJe();
			if(yk1.length()<1){
				yk1="0";
			}
			a.setMoney(Double.parseDouble(t.getLoadingPayment())-Double.parseDouble(yk1)+"");
			a.setOil(yk1);
			a.setPro(UserUtils.getUseroffice());
			a.setDelFlag("1");
			a.setSfxj(xj);
			a.setSfyk(yk);
			a.setStart(t.getContractDistance());
			a.setBill(i);
			a.setNumber(kh);
			a.setRemarks(sm);
			a.setSfzje(Double.parseDouble(xj)+Double.parseDouble(yk)+"");
			advanceService.save(a);
		}

		ajaxJson.setMsg("过账成功");
		return ajaxJson;
	}
		/**
         * 运单列表数据
         */
	@ResponseBody
	@RequiresPermissions("tms:tmsWaybill:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(TmsWaybill tmsWaybill, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){tmsWaybill.setProjectName(pro);}
		Page<TmsWaybill> page = tmsWaybillService.findPage(new Page<TmsWaybill>(request, response), tmsWaybill);
		return getBootstrapData(page);
	}
	/**
	 * 运单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsWaybill:list")
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(TmsWaybill tmsWaybill, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){tmsWaybill.setProjectName(pro);}
		tmsWaybill.setHtzt("1");
		Page<TmsWaybill> page = tmsWaybillService.findPage(new Page<TmsWaybill>(request, response), tmsWaybill);
		return getBootstrapData(page);
	}
	/**
	 * 运单报表
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(TmsWaybill tmsWaybill,String min,String max,String pro,String zydh,String hth,String cph,String sj,String dzs,String jsd) {
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			tmsWaybill.setProjectName(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				tmsWaybill.setProjectName(UserUtils.getUseroffice());
			}
		}
		tmsWaybill.setHtzt("1");
		tmsWaybill.setMin(min);
		tmsWaybill.setMax(max);
		tmsWaybill.setShipmentNumbers(zydh);
		tmsWaybill.setCode(hth);
		tmsWaybill.setPlateNumber(cph);
		tmsWaybill.setDriverName(sj);
		tmsWaybill.setArriveProvince(dzs);
		tmsWaybill.setArrive(jsd);
		List<TmsWaybill> list=tmsWaybillService.findList(tmsWaybill);
		double zjs=0.0;
		double zzl=0.0;
		double zfy=0.0;
		double zc=0.0;
		String ids="";
		for(TmsWaybill t:list){
			ids+=t.getId()+",";
            zjs+=t.getZjs();
            zzl+=Double.parseDouble(t.getWeight());
            zfy+=Double.parseDouble(t.getZfy());
			zc+=Double.parseDouble(t.getRentingCost());
		}
		NumberFormat nf = NumberFormat.getNumberInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		tmsWaybill.setZjs(zjs);
		tmsWaybill.setZfy(nf.format(zfy));
		tmsWaybill.setWeight(nf.format(zzl));
		tmsWaybill.setRentingCost(nf.format(zc));
		tmsWaybill.setZcfybl(df.format(zc/zfy));
		tmsWaybill.setMax(ids);
		list.add(tmsWaybill);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<TmsWaybill> list =new ArrayList<TmsWaybill>();
		for(String id:idd){
			list.add(tmsWaybillService.get(id));
		}

		ExportTms e=new ExportTms();
		e.exportbill(response,list);
	}
	/**
	 * 运费支出
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsWaybill:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(TmsWaybill tmsWaybill, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){tmsWaybill.setProjectName(pro);}
		tmsWaybill.setCbqr("1");

		Page<TmsWaybill> page = tmsWaybillService.findPage(new Page<TmsWaybill>(request, response), tmsWaybill);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑运单表单页面
	 */
	@RequiresPermissions(value={"tms:tmsWaybill:view","tms:tmsWaybill:add","tms:tmsWaybill:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(TmsWaybill tmsWaybill, Model model) {
		model.addAttribute("tmsWaybill", tmsWaybill);
		if(tmsWaybill.getId()!=null&&tmsWaybill.getId()!=""){
           Receipt r=receiptService.findUniqueByProperty("bill",tmsWaybill.getId());
			model.addAttribute("receipt", r);
			Accident a=accidentService.findUniqueByProperty("bill",tmsWaybill.getId());
			model.addAttribute("accident", a);
			TailAfter after=afterService.findUniqueByProperty("bill",tmsWaybill.getId());
			model.addAttribute("tailAfter", after);
			Notnode n=new Notnode();
			n.setBill(tmsWaybill.getId());
			List<Notnode> list=notnodeService.findList(n);
			if(list!=null&list.size()>0){model.addAttribute("notnode", list);}
		}
		return "modules/tms/tmsWaybillForm";
	}
	/**
	 * 创建配载
	 */
	@RequiresPermissions(value={"tms:tmsWaybill:view","tms:tmsWaybill:add","tms:tmsWaybill:edit"},logical=Logical.OR)
	@RequestMapping(value = "form3")
	public String form3(String i, Model model) {
		TmsWaybill bill=new TmsWaybill();
		TransportPlanning t=service.get(i);
//		bill.setEntrustNumber(t.getEntrustNumber());
//		tmsWaybillService.findList(bill);
		bill= (TmsWaybill) CopyUtil.Copy(bill,t,false);
		bill.setNumbers(new Date().getTime()+"");
		bill.setStowageDate(new Date());
		bill.setStatus("未回单");
		Staff s=new Staff();
		s.setProjectName(UserUtils.getUseroffice());
		List<Staff> l=staffService.findList(s);
		for(Staff staff:l){
			staff=staffService.get(staff.getId());
			if(staff.getPosition().getName().contains("调度")){
				bill.setDispatchName(staff);
			}
		}
		model.addAttribute("tmsWaybill", bill);
		model.addAttribute("id", i);
		model.addAttribute("goods", t.getMaterialInformationsList());
		return "modules/tms/3/tmsWaybillForm";
	}

	/**
	 * 创建配载
	 */
	@RequiresPermissions(value={"tms:tmsWaybill:view","tms:tmsWaybill:add","tms:tmsWaybill:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(String i, Model model) {
		TmsWaybill bill=new TmsWaybill();
		TransportPlanning t=service.get(i);
//		bill.setEntrustNumber(t.getEntrustNumber());
//		tmsWaybillService.findList(bill);
		bill= (TmsWaybill) CopyUtil.Copy(bill,t,false);
		bill.setNumbers(new Date().getTime()+"");
		bill.setStowageDate(new Date());
		bill.setStatus("未回单");
		Staff s=new Staff();
		s.setProjectName(UserUtils.getUseroffice());
		List<Staff> l=staffService.findList(s);
		for(Staff staff:l){
			staff=staffService.get(staff.getId());
			if(staff.getPosition().getName().contains("调度")){
				bill.setDispatchName(staff);
			}
		}
		model.addAttribute("tmsWaybill", bill);
		model.addAttribute("id", i);
		model.addAttribute("goods", t.getMaterialInformationsList());
		return "modules/tms/1/tmsWaybillForm";
	}
	/**
	 * 装车填写
	 */
	@RequiresPermissions(value={"tms:tmsWaybill:view","tms:tmsWaybill:add","tms:tmsWaybill:edit"},logical=Logical.OR)
	@RequestMapping(value = "form2")
	public String form2(String i, Model model) {
		TmsWaybill bill=tmsWaybillService.get(i);
		model.addAttribute("tmsWaybill", bill);
        bill.setForwardingPrice("ZC-"+bill.getCode());
		model.addAttribute("tmsMaterialsInformationList",bill.getTmsMaterialsInformationList());
		model.addAttribute("id", i);
		return "modules/tms/2/tmsWaybillForm";
	}
	/**
	 * 快捷配载装车运单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:tmsWaybill:add","tms:tmsWaybill:edit"},logical=Logical.OR)
	@RequestMapping(value = "save3")
	public AjaxJson save3(TmsWaybill tmsWaybill,HttpServletRequest req, Model model, RedirectAttributes redirectAttributes) throws Exception{

		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, tmsWaybill)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(tmsWaybill.getGuidance()==null||tmsWaybill.getGuidance().getName()==null){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		if(tmsWaybill.getCommonCarrier().length()<1||tmsWaybill.getPlateNumber().length()<1||tmsWaybill.getDriverPhone().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		if(tmsWaybill.getPayeeName().length()<1||tmsWaybill.getCardNumber().length()<1||tmsWaybill.getBankAddress().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		if(tmsWaybill.getKdPayment().length()<1||tmsWaybill.getLoadingPayment().length()<1||tmsWaybill.getReceiptCalculate().length()<1||tmsWaybill.getRentingCost().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		for(TmsMaterialsInformation t:tmsWaybill.getTmsMaterialsInformationList()){
			if(t.getVehicleQuantity().length()<1){
				j.setSuccess(false);
				j.setMsg("请检查确定无误后保存！");
				return j;
			}
		}
		NumberFormat nf = NumberFormat.getInstance();
		//新增或编辑表单保存
		String id=req.getParameter("iii");
		TransportPlanning t=service.get(id);
			tmsWaybill.setBillStatus("已装车");
			tmsWaybill.setYfk("未过账");
			tmsWaybill.setHzjs("未过账");
			tmsWaybill.setType(t.getType());
			TmsWaybill way=new TmsWaybill();
			way.setCode(t.getEntrustNumber());
			List<TmsWaybill> l=tmsWaybillService.findList(way);
			if(l==null||l.size()<1){
				tmsWaybill.setCode(t.getEntrustNumber()+"-1");
			}else{tmsWaybill.setCode(t.getEntrustNumber()+"-"+(l.size()+1));}
		tmsWaybill.setForwardingPrice("ZC-"+tmsWaybill.getCode());
		tmsWaybillService.save(tmsWaybill);//保存

		t.setStatus("已配载");
		boolean bol=true;
		double weight=0.0;
		List<MaterialInformations> list=t.getMaterialInformationsList();
		for(MaterialInformations m:list){
			String i=req.getParameter(m.getId());
			if(i==null||i==""){
				i="0";
			}
			int num=Integer.parseInt(i);
			if(num==0){
				String m0=m.getRemain();
				if(!m.getRemain().equals("0")){
					bol=false;}

				continue;
			}
			int n=Integer.parseInt(m.getRemain());
			if(num<n){
				bol=false;
			}
			TmsMaterialsInformation ma=new TmsMaterialsInformation();
			ma.setWaybill(tmsWaybill);
			Goods g=goodsService.get(m.getGoods().getId());
			ma.setNumber(m.getNumber());
			ma.setName(g);
			ma.setType(m.getType());
			ma.setIdx(m.getIdx());
			ma.setCoding(m.getCoding());
			ma.setDepot(m.getDepot());
			ma.setSpecification(m.getSpecification());
			ma.setId(UUID.randomUUID().toString().replace("-",""));
			ma.setVehicleQuantity(num+"");
			ma.setLoadingQuantity(num+"");

			ma.setWeight(nf.format(Double.parseDouble(g.getGrossWeight())*num).replaceAll(",",""));
			ma.setVolume(nf.format(Double.parseDouble(g.getVolume())*num).replaceAll(",",""));
			materialsInformationMapper.insert(ma);
			weight+=Double.parseDouble(ma.getWeight());
			m.setVehicleQuantity((num+Integer.parseInt(m.getVehicleQuantity()==null?"0":m.getVehicleQuantity()))+"");
			m.setRemain((Integer.parseInt(m.getRemain())-num)+"");
			informationsMapper.update(m);}
		if(bol){
			t.setPlanStatus("计划完成");
			t.setWf(0.0);
		}else{
			t.setWf(Double.parseDouble(nf.format(t.getWf()-weight).replaceAll(",","")));
			t.setPlanStatus("部分计划");
		}
		service.save(t);

		j.setSuccess(true);
		j.setMsg("保存运单成功");
		return j;
	}
	/**
	 * 创建配载
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:tmsWaybill:add","tms:tmsWaybill:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(TmsWaybill tmsWaybill,HttpServletRequest req, Model model, RedirectAttributes redirectAttributes) throws Exception{

		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, tmsWaybill)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		String id=req.getParameter("iii");
		TransportPlanning t=service.get(id);
		if(tmsWaybill.getIsNewRecord()){
			tmsWaybill.setBillStatus("已配载");
			tmsWaybill.setBx("未投保");
			tmsWaybill.setType(t.getType());
			TmsWaybill way=new TmsWaybill();
			way.setCode(t.getEntrustNumber());
			List<TmsWaybill> l=tmsWaybillService.findList(way);
			if(l==null||l.size()<1){
				tmsWaybill.setCode(t.getEntrustNumber()+"-1");
			}else{tmsWaybill.setCode(t.getEntrustNumber()+"-"+(l.size()+1));}
		}else{tmsWaybill.setBillStatus("已装车");}
//		String a=tmsWaybill.getKdPayment();
//		String b=tmsWaybill.getLoadingPayment();
//		String c=tmsWaybill.getReceiptCalculate();
//		String d=tmsWaybill.getRentingCost();
//		if(a==null||a==""){
//			a="0";
//		}	if(b==null||b==""){
//			b="0";
//		}	if(c==null||c==""){
//			c="0";
//		}if(d==null||d==""){
//			d="0";
//		}
//		tmsWaybill.setTotalCost((Integer.parseInt(a)+Integer.parseInt(b)+Integer.parseInt(c))+"");
//		tmsWaybill.setFreight((Integer.parseInt(a)+Integer.parseInt(b)+Integer.parseInt(c)+Integer.parseInt(d))+"");
		tmsWaybillService.save(tmsWaybill);//保存

		t.setStatus("已配载");
		boolean bol=true;
		List<MaterialInformations> list=t.getMaterialInformationsList();
		double weight=0.0;
		for(MaterialInformations m:list){
			String i=req.getParameter(m.getId());
			if(i==null||i==""){
				i="0";
			}
			int num=Integer.parseInt(i);
			if(num==0){
				String m0=m.getRemain();
				if(!m.getRemain().equals("0")){
					bol=false;}

				continue;
			}
			int n=Integer.parseInt(m.getRemain());
            if(num<n){
            	bol=false;
			}
			TmsMaterialsInformation ma=new TmsMaterialsInformation();
			ma.setWaybill(tmsWaybill);
			Goods g=goodsService.get(m.getGoods().getId());
			ma.setNumber(m.getNumber());
			ma.setName(g);
			ma.setType(m.getType());
			ma.setIdx(m.getIdx());
			ma.setCoding(m.getCoding());
			ma.setDepot(m.getDepot());
			ma.setSpecification(m.getSpecification());
			ma.setId(UUID.randomUUID().toString().replace("-",""));
			ma.setVehicleQuantity(num+"");
			ma.setLoadingQuantity(num+"");
			NumberFormat nf = NumberFormat.getInstance();
			ma.setWeight(nf.format(Double.parseDouble(g.getGrossWeight())*num).replaceAll(",",""));
			ma.setVolume(nf.format(Double.parseDouble(g.getVolume())*num).replaceAll(",",""));
			materialsInformationMapper.insert(ma);
			weight+=Double.parseDouble(ma.getWeight());
			m.setVehicleQuantity((num+Integer.parseInt(m.getVehicleQuantity()==null?"0":m.getVehicleQuantity()))+"");
			m.setRemain((Integer.parseInt(m.getRemain())-num)+"");
			informationsMapper.update(m);}
		NumberFormat nf = NumberFormat.getInstance();
			if(bol){
			t.setWf(0.0);
			t.setPlanStatus("计划完成");

		}else{
				t.setWf(Double.parseDouble(nf.format(t.getWf()-weight).replaceAll(",","")));
				t.setPlanStatus("部分计划");}
		service.save(t);
		j.setSuccess(true);
		j.setMsg("保存运单成功");
		return j;
	}
	/**
	 * 保存运单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:tmsWaybill:add","tms:tmsWaybill:edit"},logical=Logical.OR)
	@RequestMapping(value = "save1")
	public AjaxJson save1(TmsWaybill tmsWaybill,HttpServletRequest req, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, tmsWaybill)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(tmsWaybill.getPayeeName().length()<1||tmsWaybill.getCardNumber().length()<1||tmsWaybill.getBankAddress().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		if(tmsWaybill.getKdPayment().length()<1||tmsWaybill.getLoadingPayment().length()<1||tmsWaybill.getReceiptCalculate().length()<1||tmsWaybill.getRentingCost().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		for(TmsMaterialsInformation t:tmsWaybill.getTmsMaterialsInformationList()){
			if(t.getLoadingQuantity().length()<1){
				j.setSuccess(false);
				j.setMsg("请检查确定无误后保存！");
				return j;
			}
		}
		double weight=0.0;
		NumberFormat nf = NumberFormat.getInstance();
		TransportPlanning ts=transportPlanningService.findUniqueByProperty("pid",tmsWaybill.getPid());
		List<MaterialInformations> l=transportPlanningService.get(ts.getId()).getMaterialInformationsList();
		List<TmsMaterialsInformation> list=tmsWaybill.getTmsMaterialsInformationList();
        if(tmsWaybill.getBillStatus().equals("已配载")){

		for(TmsMaterialsInformation t:list){
			int i=(Integer.parseInt(t.getVehicleQuantity())-Integer.parseInt(t.getLoadingQuantity()));

			if(Integer.parseInt(t.getVehicleQuantity())>Integer.parseInt(t.getLoadingQuantity())){

				Goods g=new Goods();
				g.setCode(t.getCoding());
				g.setProject(UserUtils.getUseroffice());
				g=goodsService.findList(g).get(0);
				weight+=i*Double.parseDouble(g.getGrossWeight());

				t.setWeight(nf.format(Double.parseDouble(g.getGrossWeight())*Integer.parseInt(t.getLoadingQuantity())).replaceAll(",",""));
				t.setVolume(nf.format(Double.parseDouble(g.getVolume())*Integer.parseInt(t.getLoadingQuantity())).replaceAll(",",""));
				materialsInformationMapper.update(t);
				for(MaterialInformations m:l){
                if(m.getCoding().equals(t.getCoding())){
					m.setRemain((Integer.parseInt(m.getRemain())+i)+"");
                    m.setVehicleQuantity((Integer.parseInt(m.getVehicleQuantity())-i)+"");
					materialInformationsMapper.update(m);
					ts.setPlanStatus("部分计划");
				}
				}
			}
		}}
		//新增或编辑表单保存
		tmsWaybill.setBillStatus("已装车");
		tmsWaybill.setYfk("未过账");
		tmsWaybill.setHzjs("未过账");

		ts.setWf(Double.parseDouble(nf.format(ts.getWf()+weight).replaceAll(",","")));
		tmsWaybillService.save(tmsWaybill);//保存
		transportPlanningService.save(ts);

		j.setSuccess(true);
		j.setMsg("保存运单成功");
		return j;
	}

	@ResponseBody
	@RequestMapping("ckd")
	public String ckd(String ids){
		   String[] id=ids.split(",");
		   for(String i:id){
			TmsWaybill t=tmsWaybillService.get(i);
			Outbound outbound=outboundService.findUniqueByProperty("entrust_number",t.getCode());
			if(outbound==null){
			Outbound o=new Outbound();
			o= (Outbound) CopyUtil.Copy(o,t,false);
			o.setExternalOrder(t.getCode());
			String name=t.getProjectName();
			Project p=projectService.findUniqueByProperty("name",name);
			UpCustomers up=new UpCustomers();
			up.setProject(p);
			List<UpCustomers> li=upCustomersService.findList(up);
			if(li!=null&&li.size()>0){
				UpCustomers u=li.get(0);
                o.setOwnerName(u.getName());
                o.setOwnerAddress(u.getAddress());
                o.setOwnerCode(u.getAbbreviation());
                o.setOwnerPerson(u.getPerson());
			}
        o.setCreateDate(new Date());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String code=UserUtils.getUserAre()+"CK"+sdf.format(new Date());
				Outbound ou=new Outbound();
				ou.setCode(code);
				List<Outbound> lis=outboundService.findList(ou);
				if(lis==null||lis.size()<1){
					o.setCode(code+"001");
				}else{
					if(lis.size()/10==0){
						o.setCode(code+"00"+(lis.size()+1));
					}else
					if(lis.size()/100==0){
						o.setCode(code+"0"+(lis.size()+1));
					}else{o.setCode(code+(lis.size()+1));}

				}

		//o.setCode(new Date().getTime()+"");
		o.setType("销售出库");
				if(t.getType().contains("调拨")){
					o.setType("调拨出库");
				}
				o.setStatus("已创建");
		o.setProjectName(t.getProjectName());
		o.setDate(new Date());
		outboundService.save(o);
		List<TmsMaterialsInformation> l=t.getTmsMaterialsInformationList();
		int a=0;
		Double b=0.0;
		Double c=0.0;
				String num="";
		for(TmsMaterialsInformation m:l){
			a+=Integer.parseInt(m.getVehicleQuantity());
			b+=Double.parseDouble(m.getWeight());
			c+=Double.parseDouble(m.getVolume());
			Storehouse storehouse=new Storehouse();
			storehouse.setIdx(m.getIdx());
			storehouse.setCode(m.getCoding());
			storehouse.setName(m.getName());
            storehouse.setDeliver("0");
            storehouse.setPicking("0");
            storehouse.setStatus("未拣货");
            storehouse.setNumber(m.getNumber());
            storehouse.setDistribution(m.getVehicleQuantity());
            storehouse.setOrderNumber(m.getVehicleQuantity());
            storehouse.setPacking(m.getType());
            storehouse.setUnit("桶");
           storehouse.setOutbound(o);
           storehouse.setId(UUID.randomUUID().toString().replace("-",""));
           storehouseMapper.insert(storehouse);
			if(!num.contains(storehouse.getNumber())){num+=storehouse.getNumber()+",";}
		}
		o.setVolume(c+"");
		o.setGrossWeight(b+"");
		o.setAmount(a+"");
		o.setErpOrder(num);
		outboundService.save(o);
      t.setBillStatus("已生成出库单");
      tmsWaybillService.save(t);}}
		return "";
	}
	@ResponseBody
	@RequestMapping("qxpz")
	public String qxpz(String i){

		return tmsWaybillService.qxpz(i);
	}

	/**
	 * 生成合同
	 * @param i
	 * @return
	 */
	@ResponseBody
	@RequestMapping("scht")
	public String scht(String i){
		TmsWaybill t=tmsWaybillService.get(i);
		t.setBillStatus("已生成合同");
		t.setHtzt("1");
		t.setBx("未投保");
		t.setFhrq(new Date());
		double a=0.0;
		String th="";
		Double weight=0.0;
		List<TmsMaterialsInformation> l=t.getTmsMaterialsInformationList();
		for(TmsMaterialsInformation tms:l){
			weight+=Double.parseDouble(tms.getWeight().replaceAll(",",""));
			double amount=Double.parseDouble(tms.getLoadingQuantity());
			Goods g=goodsService.get(tms.getName().getId());
			int bl=Integer.parseInt(g.getProportion());
			double c=amount/bl;
			a+=c;
			th+=tms.getNumber()+",";
		}
		NumberFormat nf = NumberFormat.getNumberInstance();
		t.setWeight(nf.format(weight).replaceAll(",",""));
		t.setZjs(a);
		t.setTh(th);
		List<TmsAdditionalCharge> charges=t.getTmsAdditionalChargeList();
		Double xxf=0.0;
		Double bxf=0.0;
		Double qtsr=0.0;
		Double fhp=0.0;
		Double zxf=0.0;
		Double qtzc=0.0;
		Double fhpsr=0.0;
		for(TmsAdditionalCharge t1:charges){
			t1=tmsAdditionalChargeMapper.get(t1.getId());
			if(t1.getBalanceType().contains("防护用品支出")){
				fhp+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("防护用品收入")){
				fhpsr+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("装卸费支出")){
				zxf+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("其他支出")){
				qtzc+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("信息费收入")){
				xxf+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("保险费收入")){
				bxf+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("其他收入")){
				qtsr+=Double.parseDouble(t1.getMoney());
			}
		}
		t.setFhpsr(fhpsr+"");
		t.setFhpzc(fhp+"");
		t.setZxfzc(zxf+"");
		t.setQtzc(qtzc+"");
		t.setBxfsr(bxf+"");
		t.setXxfsr(xxf+"");
		t.setQtsr(qtsr+"");
		Double xj=Double.parseDouble(t.getLoadingPayment())-Double.parseDouble(t.getLoadingJe());
		t.setPaymentNumber(xj+"");
		Double zfy=Double.parseDouble(t.getFreight())+fhp+zxf+qtzc;
		t.setZfy(zfy+"");
//		NumberFormat nf = NumberFormat.getNumberInstance();
		// 保留两位小数
		nf.setMaximumFractionDigits(2);
		DecimalFormat df = new DecimalFormat("0.00%");
		t.setYsdj( nf.format(zfy/weight));
		t.setZcfybl(df.format(Double.parseDouble(t.getRentingCost())/zfy));
		tmsWaybillService.save(t);
		boolean bol=true;
		TransportPlanning tr=transportPlanningService.findUniqueByProperty("pid",t.getPid());
		if(!tr.getPlanStatus().equals("计划完成")){
			bol=false;
		}
       if(bol){
		TmsWaybill tms=new TmsWaybill();
		tms.setPid(t.getPid());
		List<TmsWaybill> bills=tmsWaybillService.findList(tms);

		for(TmsWaybill bill:bills){
			if(bill.getHtzt().equals("0")){
				bol=false;
				break;
			}
		}}
if(bol){
	Planning p= planningService.get(t.getPid());
	p.setJftj("满足");
	planningService.save(p);
}
		return "";
	}


	/**
	 * 取消合同
	 * @param i
	 * @return
	 */
	@ResponseBody
	@RequestMapping("qxht")
	public String qxht(String i){
		TmsWaybill t=tmsWaybillService.get(i);
		if(t.getYfk().equals("已过账")||t.getHzjs().equals("已过账")){
			return "error";
		}else{
          Planning p= planningService.get(t.getPid());
          p.setJftj("不满足");
          planningService.save(p);
			BillAdd b=billAddService.findUniqueByProperty("zydh",t.getShipmentNumbers());
			billAddService.delete(b);
			t.setBillStatus("已装车");
			t.setHtzt("0");
			t.setZt("1");
			t.setCbqr("0");
			tmsWaybillService.save(t);
			jdbc.execute("delete from tms_accident where bill='"+t.getId()+"'");
			jdbc.execute("delete from tms_notnode where bill='"+t.getId()+"'");
			jdbc.execute("delete from tms_receipt where bill='"+t.getId()+"'");
			jdbc.execute("delete from tms_tail_after where bill='"+t.getId()+"'");
			return "";

		}

	}

	/**
	 * 成本确认
	 * @param i
	 * @return
	 */
	@ResponseBody
	@RequestMapping("cbqr")
	public String cbqr(String i){
		TmsWaybill t=tmsWaybillService.get(i);
		t.setCbqr("1");
		tmsWaybillService.save(t);

		BillAdd add=new BillAdd();
		add.setPro(t.getProjectName());
		add.setZydh(t.getShipmentNumbers());
		add.setBxfsr(t.getBxfsr());
		add.setXxfsr(t.getXxfsr());
		add.setFhpsr(t.getFhpsr());
		add.setQtsr(t.getQtsr());
		add.setZch(t.getForwardingPrice());
		add.setHth(t.getCode());
		add.setFhpzc(t.getFhpzc());
		add.setZxfzc(t.getZxfzc());
		add.setQtzc(t.getQtzc());
		add.setDate(new Date());
		add.setStatus("已入账");
		add.setRz(new Date());
		billAddService.save(add);
		NumberFormat nf = NumberFormat.getInstance();

		Yue yue=yueService.findUniqueByProperty("pro",UserUtils.getUseroffice());
		Double l=Double.parseDouble(add.getXxfsr())+Double.parseDouble(add.getBxfsr())+Double.parseDouble(add.getFhpsr())+Double.parseDouble(add.getQtsr())-Double.parseDouble(add.getFhpzc())-Double.parseDouble(add.getZxfzc())-Double.parseDouble(add.getQtzc());
		yue.setXj(nf.format(Double.parseDouble(yue.getXj())+l).replaceAll(",",""));
		yue.setZje(nf.format(Double.parseDouble(yue.getZje())+l).replaceAll(",",""));
		yueService.save(yue);
		return "";
	}
	/**
	 * 删除运单
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsWaybill:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(TmsWaybill tmsWaybill, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		tmsWaybillService.delete(tmsWaybill);
		j.setMsg("删除运单成功");
		return j;
	}
	
	/**
	 * 批量删除运单
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsWaybill:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			tmsWaybillService.delete(tmsWaybillService.get(id));
		}
		j.setMsg("删除运单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsWaybill:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(TmsWaybill tmsWaybill, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "运单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TmsWaybill> page = tmsWaybillService.findPage(new Page<TmsWaybill>(request, response, -1), tmsWaybill);
    		new ExportExcel("运单", TmsWaybill.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出运单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public TmsWaybill detail(String id) {
		return tmsWaybillService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:tmsWaybill:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TmsWaybill> list = ei.getDataList(TmsWaybill.class);
			for (TmsWaybill tmsWaybill : list){
				try{
					tmsWaybillService.save(tmsWaybill);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条运单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条运单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入运单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/tmsWaybill/?repage";
    }
	
	/**
	 * 下载导入运单数据模板
	 */
	@RequiresPermissions("tms:tmsWaybill:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "运单数据导入模板.xlsx";
    		List<TmsWaybill> list = Lists.newArrayList(); 
    		new ExportExcel("运单数据", TmsWaybill.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/tmsWaybill/?repage";
    }


	/**
	 * 调用打印页面
	 */
	@RequestMapping(value = "dayin")
	public String dayin(HttpServletRequest request, String ids, Model model) throws Exception {

		//模版文件目录
		String templateFile = request.getSession().getServletContext().getRealPath("static/common/pdf/stenail/waybillstenail.pdf");

		//要合并的pdf所在文件夹
		String folder = request.getSession().getServletContext().getRealPath("static/common/pdf/example/");

		PrintWayBill printWayBill = new PrintWayBill();
		//用于存放需要合并的pdf文件名
		List<String> filelist = new ArrayList<String>();
		//多条数据
		String idArray[] = ids.split(",");
		String pro=UserUtils.getUseroffice();
		Project project=projectService.findUniqueByProperty("name",pro);
		UpCustomers u=upCustomersService.findUniqueByProperty("project",project.getId());
		u=upCustomersService.get(u.getId());
		TakeAddress ck=new TakeAddress();
		for(TakeAddress t:u.getTakeAddressList()){
			if(t.getStore().contains("库")){
				ck=t;
			}
		}
		for (String id : idArray) {
//			TransportPlanning t=transportPlanningService.get(id);
//			TmsWaybill tm=new TmsWaybill();
//			tm.setCode(t.getEntrustNumber());
//			List<TmsWaybill> l=tmsWaybillService.findList(tm);
//			for(TmsWaybill tmsWaybill:l){
			TmsWaybill tmsWaybill=tmsWaybillService.get(id);
			tmsWaybill.setHtcs(tmsWaybill.getHtcs()+1);
			tmsWaybillService.save(tmsWaybill);

				List<Map<String,Object>> list=jdbc.queryForList("SELECT a.type ,sum(a.loading_quantity/goods.proportion) as gross,SUM(a.weight)as weight, SUM(a.volume)  as volume,a.depot as depot FROM tms_materials_information a LEFT JOIN infor_goods goods on goods.id=a.name  where a.waybill='"+tmsWaybill.getId() +"' GROUP BY a.type,a.depot;");
				//时间戳命名要合并的pdf并加入list
				String filewei = "order"+new Date().getTime() + ".pdf";
				//要合并的pdf目录
				String outFile = folder + "/"+filewei;
				File file = new File(outFile);
				if (!file.exists()) {
					try {
						file.createNewFile();
						System.out.println("创建成功!");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				printWayBill.updatePdfa(tmsWaybill,ck, list, templateFile, file);
				filelist.add(filewei);
			//}



		}

		//合并后pdf所在文件夹
		String outPdfFileqian = request.getSession().getServletContext().getRealPath("static/common/pdf/print/");
		//合并后pdf文件目录
		String outPdfFile = outPdfFileqian+"/mergepdfbill"+new Date().getTime() + ".pdf";
		//合并pdf方法
		printWayBill.mergePdf(folder, outPdfFile,filelist);
//定时删除合并前的文件以及合并后的文件
		Timer timer = new Timer();//实例化Timer类
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					FileUtil.deleteFile(outPdfFile);
					for (int i = 0; i < filelist.size(); i++){
						FileUtil.deleteFile(folder + File.separator + filelist.get(i));
						System.out.println("删除文件成功");}

				} catch (Exception e) {

				} finally {
					this.cancel();
				}

			}
		}, 50000);//五万毫秒 50秒
		//将合并后的pdf目录传到jsp供读取
		request.setAttribute("outPdfFile",outPdfFile);
		return "modules/tms/print/pdfbill";
	}


	/**
	 * 调用打印页面
	 */
	@RequestMapping(value = "day")
	public String day(HttpServletRequest request, String ids, Model model) throws Exception {

		//模版文件目录
		String templateFile = request.getSession().getServletContext().getRealPath("static/common/pdf/stenail/zuche.pdf");

		//要合并的pdf所在文件夹
		String folder = request.getSession().getServletContext().getRealPath("static/common/pdf/example/");

		PrintWayBill printWayBill = new PrintWayBill();
		String pro=UserUtils.getUseroffice();
		Project project=projectService.findUniqueByProperty("name",pro);
		UpCustomers u=upCustomersService.findUniqueByProperty("project",project.getId());
		u=upCustomersService.get(u.getId());
		String ck="";
		for(TakeAddress t:u.getTakeAddressList()){
			if(t.getStore().contains("库")){
				ck=t.getAddress();
			}
		}
		//用于存放需要合并的pdf文件名
		List<String> filelist = new ArrayList<String>();
		//多条数据
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			TmsWaybill tmsWaybill=tmsWaybillService.get(id);
			tmsWaybill.setZccs(tmsWaybill.getZccs()+1);
			tmsWaybillService.save(tmsWaybill);
			//时间戳命名要合并的pdf并加入list
			String filewei = "zuche"+new Date().getTime() + ".pdf";
			//要合并的pdf目录
			String outFile = folder + "/"+filewei;
			File file = new File(outFile);
			if (!file.exists()) {
				try {
					file.createNewFile();
					System.out.println("创建成功!");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			printWayBill.updatePdfa1(tmsWaybill,ck,  templateFile, file);
			filelist.add(filewei);
			//}



		}

		//合并后pdf所在文件夹
		String outPdfFileqian = request.getSession().getServletContext().getRealPath("static/common/pdf/print/");
		//合并后pdf文件目录
		String outPdfFile = outPdfFileqian+"/zuche"+new Date().getTime() + ".pdf";
		//合并pdf方法
		printWayBill.mergePdf(folder, outPdfFile,filelist);
//定时删除合并前的文件以及合并后的文件
		Timer timer = new Timer();//实例化Timer类
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					FileUtil.deleteFile(outPdfFile);
					for (int i = 0; i < filelist.size(); i++){
						FileUtil.deleteFile(folder + File.separator + filelist.get(i));
						System.out.println("删除文件成功");}

				} catch (Exception e) {

				} finally {
					this.cancel();
				}

			}
		}, 50000);//五万毫秒 50秒
		//将合并后的pdf目录传到jsp供读取
		request.setAttribute("outPdfFile",outPdfFile);
		return "modules/tms/print/1/pdfzuche";
	}
}